package cz.semjobKB.extract.service;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cz.semjobKB.extract.api.IExtractTextService;
import cz.semjobKB.extract.api.impl.ExctractFromPpt;
import cz.semjobKB.extract.api.impl.ExtractFromDoc;
import cz.semjobKB.extract.api.impl.ExtractFromPdf;

/**
 * Service that allows user to extract plain text form Microsoft Word, Powerpoint or PDF file
 * @author synergy
 *
 */
@Service
public class TextExtractorService implements IExtractTextService {

	private final static Logger logger = Logger.getLogger(TextExtractorService.class);

	@Autowired
	private ExtractFromDoc extractFromDoc;
	
	@Autowired
	private ExctractFromPpt extractFromPpt;
	
	@Autowired
	private ExtractFromPdf extractFromPdf;

	
	public File extractText(String filePath){

		logger.info("Starting extracting text from file: " + filePath);
		File file;
		File targetFile;
		try {
			file = new File(filePath);		
			//Check if the file has been processed already
			targetFile = getAlreadyProcessedText(file);
			if (targetFile != null) {
				String alreadyProcessedText = FileUtils.readFileToString(targetFile);
				if(alreadyProcessedText != null && !alreadyProcessedText.isEmpty()) {
					return targetFile;
				}
			}
			if (file != null) {		
				switch (getExtension(file)) {
				case "ppt": {
					String text = extractFromPpt.extractText(file);
					targetFile = createTextFile(file, text);
					return targetFile;

				}
				case "pdf": {
					String text =extractFromPdf.extractText(file);
					targetFile = createTextFile(file, text);
					return targetFile;
				}
				case "doc": {
					String text = extractFromDoc.extractText(file);
					targetFile = createTextFile(file, text);
					return targetFile;
				}
				default: logger.warn("File extension: " + getExtension(file) + " not supported.");
				return null;
				}
			}
		} catch (IOException ex) {
			logger.error("Couldnt extract text from file. File: " + filePath + "\n"  + ex.getMessage());			
		}
		return null;
	}

	/** 
	 * Stores an extracted plain text into a file that has the same name as input file
	 */
	private File createTextFile(File origDocument, String text) throws IOException {
		String textFilePath = origDocument.getParent() + File.separator + "txt" + 
				File.separator + FilenameUtils.removeExtension(origDocument.getName()) + ".txt";
		File textFile = new File(textFilePath);
		FileUtils.writeStringToFile(new File(textFilePath), text);
		return textFile;
	}

	/**
	 * Returns file that contains a plain text of a given input file if this file exists
	 */
	private File getAlreadyProcessedText(File file) throws IOException {
		String textFilePath = file.getParent() + File.separator + "txt" + 
				File.separator + FilenameUtils.removeExtension(file.getName()) + ".txt";
		File textFile = new File(textFilePath);
		if (textFile.exists()) {
			return textFile;
		}
		return null;
	}

	/**
	 * Returns the extension of a given file 
	 */
	private String getExtension(File file) {

		String name = file.getName();
		int dotPossition = name.lastIndexOf(".");

		if(dotPossition > -1 && dotPossition < name.length()) {
			return name.substring(dotPossition + 1);
		}
		return null;

	}

}
